import axios from 'axios';
import router from '@/router/index';
import { Message } from 'element-ui';

const service = axios.create({
	baseURL: g_config.baseService_URL, // url = base url + request url
	// baseURL: baseUrl,
	withCredentials: false, // send cookies when cross-domain requests
	// timeout: 8000, // request timeout
});
// 请求头中添加token
service.interceptors.request.use(
	config => {
		let token = localStorage.getItem('token');
		if (token) config.headers.Authentication = token;
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

// response 请求拦截 401:token失效
service.interceptors.response.use(
	response => {
		if (response.data.code == 200) {
			return response;
		}
	},
	error => {
		if (error.response.data.code == 401) {
			Message({
				message: error.response.data.msg,
				type: 'error',
				duration: 5 * 1000,
			});
			let temp;
			if (router.currentRoute.path != '/login') temp = router.currentRoute.path;
			router.push({
				path: '/login',
				query: {
					nextPage: temp, // 传参，登录后直接跳转的页面
				},
			});
		}
		return Promise.reject(error.response);
	}
);

export default service;
